<template>
  <div class="energy_consume">
    <div class="btn-con">
      <div class="btn-bord">
        <!-- 选择月份 -->
        <div v-if="!dark" class="rightBox">
          <px-select v-model="aaa" placeholder="请选择" filterable class="selectMonth" style="width: 120px">
            <px-option v-for="item in aaaList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
          <px-select v-model="queryParams.month" filterable placeholder="选择月份" class="selectMonth" @change="changeMonth">
            <px-option v-for="item in monthsArray" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
          <px-button v-if="monthlyDetails" @click="handleDown('month')">
            导出<px-icon class="px-icon--right">
              <Download />
            </px-icon>
          </px-button>
        </div>
        <div style="height: 100%">
          <hotWaterBar
            :key="midKey - 10"
            :dark="dark"
            title="机械科-高温热水消耗分析预测"
            :unit="getUnit"
            :dataList="monthlyDetails"
            :width="642"
            :height="167"
            :options="monthOptions"
            :timeFrame="queryParams.dateRangeItem"
            :month="queryParams.month"
          />
        </div>
      </div>
    </div>
    <!-- <div>
      <EnergyConsumeRank />
    </div> -->
  </div>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, nextTick, computed, onUnmounted } from "vue";
import { useRouterStoreHook } from "@/store/modules/router";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import { emitter } from "@/utils/mitt";
import { queryDictData } from "@/api/common";
import { PxMessage } from "px-ui";
// import rowBord from "../components/rowBord.vue";
// import bordBarchartYear from "../components/bordBarchartYear.vue";
import hotWaterBar from "./hotWaterBar.vue";
import { getPredictDataMachine, exportExcelYear, exportExcelMonth } from "@/api/energy/predictApi";
// import EnergyConsumeRank from "@/views/common/energy/components/EnergyConsumeRank.vue";
import { Download } from "@px-ui/icons-vue";

const { proxy }: any = getCurrentInstance();
const emit = defineEmits(["monthChange"]);
const midKey = ref(Date.now());

interface Props {
  dark?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  dark: false
});

const systemList = ref<any>([]);

const monthOptions = ref<UtilsEChartsOption>({});
const yearOptions = ref<UtilsEChartsOption>({});

const currentYear = new Date().getFullYear();
const monthsArray = ref(Array.from({ length: 12 }, (_, index) => ({ value: index + 1, label: `${index + 1}月` })));

const getUnit = computed(() => {
  switch (queryTypeParams.value.energyType) {
    case 1:
      return "MWh"; // 电
    case 2:
      return "m³"; // 水
    case 3:
      return "t"; // 蒸汽
    case 7:
      return "t"; // 热水
    case 8:
      return "GJ"; // 热水
    case 4:
      return "t"; // 柴油
    case 5:
      return "Nm³"; // 大宗气
    case 6:
      return "Nm³"; // 大宗气
    case 9:
      return "Nm³"; // 大宗气
    case 10:
      return "Nm³"; // 大宗气
    case 11:
      return "Nm³"; // 大宗气
    case 12:
      return "Nm³"; // 大宗气
    case 13:
      return "Nm³"; // 大宗气
    case 14:
      return "Nm³"; // 大宗气
    case 15:
      return "Nm³"; // 大宗气

    default:
      return "MWh";
  }
});

const aaa = ref("1");
const aaaList = ref([
  {
    label: "高温热水",
    value: "1"
  }
]);

const getIcon = computed(() => {
  switch (queryTypeParams.value.energyType) {
    case 1:
      return "icon_electricity"; // 电
    case 2:
      return "icon_water"; // 水
    case 3:
      return "icon_steam"; // 蒸汽
    case 7:
      return "icon_hot_water"; // 热水
    case 8:
      return "icon_hot_water"; // 热水
    case 4:
      return "icon_diesel"; // 柴油
    case 5:
      return "icon_gas"; // 大宗气
    case 6:
      return "icon_ng"; // 大宗气
    case 9:
      return "icon_cda"; // 大宗气
    case 10:
      return "icon_n2"; // 大宗气
    case 11:
      return "icon_h2"; // 大宗气
    case 12:
      return "icon_o2"; // 大宗气
    case 13:
      return "icon_ar"; // 大宗气
    case 14:
      return "icon_he"; // 大宗气
    case 15:
      return "icon_co2"; // 大宗气

    default:
      return "icon_electricity";
  }
});

// 年度能源消耗趋势
const dataList = ref<any>([
  {
    name: `${currentYear - 2}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  },
  {
    name: `${currentYear - 1}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  },
  {
    name: `${currentYear}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  },
  {
    name: `${currentYear + 1}`,
    icon: getIcon,
    unit: getUnit,
    valueFormat: null,
    yoy: null
  }
]);
// 年度总览
const annualOverview = ref(null);
// 月度明细
const monthlyDetails = ref(null);
type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

const labelLayoutFn = (data: any, title: string) => {
  const options: UtilsEChartsOption = {
    // color: ["#3B82F6", "#14C7C7"],
    title: {
      text: title,
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true,
      axisPointer: {
        type: "shadow"
      },
      textStyle: {
        align: "left"
      },
      formatter: params => {
        let relVal = params[0].name;
        for (let i = 0; i < params.length; i++) {
          relVal += `<br/>${params[i].marker} ${params[i].seriesName} ${params[i].value} ${params[i].seriesName === "预测误差" ? "%" : getUnit.value}`;
        }
        return relVal;
      }
    },
    legend: {
      // type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      // data: props.areaList.map((item: any) => item.name),
      data: ["实际", "预测", "预测误差"]
      // orient: "horizontal"
    },
    grid: {
      left: "0",
      top: "15%",
      right: "0",
      bottom: "0",
      containLabel: true
    },
    // dataset: {
    //   source: arr
    // },
    xAxis: {
      type: "category",
      data: data.abscissa.map(e => e.substring(3)) || []
      // data: ["24/01", "24/02", "24/03", "24/04", "24/05", "24/06", "24/07", "24/08", "24/09", "24/10", "24/11", "24/12"]
    },
    yAxis: [
      {
        type: "value",
        name: `单位：${getUnit.value}`,
        alignTicks: true,
        nameTextStyle: {
          align: "left"
        },
        axisLine: {
          show: true,
          lineStyle: {
            width: 1
          }
        }
      },
      {
        type: "value",
        // name: `%`,
        // position: "left",
        axisLabel: {
          formatter: function (value) {
            return value.toFixed(2) + "%";
          }
        },
        alignTicks: true,
        // offset: 50,
        axisLine: {
          show: true,
          lineStyle: {
            width: 1
          }
        }
      }
    ],
    series: [
      {
        name: "实际",
        type: "bar",
        barWidth: 16,
        itemStyle: {
          color: "#3B82F6"
        },
        yAxisIndex: 0,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        data: data.kwhCoordinate ? data.kwhCoordinate.map(v => Number(v)) : []
        // data: [123, 23, 123, 223, 120, 222, 554, 233, 123, 234, 111, 432]
      },
      {
        name: "预测",
        type: "bar",
        barWidth: 16,
        yAxisIndex: 0,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#603BF6"
        },
        data: data.kwhPredictCoordinate ? data.kwhPredictCoordinate.map(v => Number(v)) : []
        // data: [123, 23, 123, 223, 120, 222, 554, 233, 123, 234, 111, 432]
      },
      {
        name: "预测误差",
        type: "line",
        yAxisIndex: 1,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#FFCA45"
        },
        data: data.radioCoordinate ? data.radioCoordinate.map(v => Number(v)) : []
        // data: [11, 12, 14, 16, 8, 9, 15, 7, 22, 13, 7, 20]
      }
    ]
  };
  return options;
};
// 总排名
const labelLayoutAreaFn = async () => {
  const title = "";
  const param = {
    timeFrame: queryParams.value.dateRangeItem,
    month: queryParams.value.month,
    energyType: 8
    // factoryArea: queryParams.value.factory
  };
  const res: any = await getPredictDataMachine(param);
  if (res.monthlyDetails) {
    // dataList.value = res.annualEnergyConsumptionTrend.trendNodeList.map(item => {
    //   item.icon = getIcon.value;
    //   return item;
    // });
    annualOverview.value = res.annualOverview;
    monthlyDetails.value = res.monthlyDetails;
  } else {
    // dataList.value = [];
    annualOverview.value = null;
    monthlyDetails.value = null;
  }

  const data = [];
  if (res.annualOverview && res.annualOverview.annualGraph) {
    yearOptions.value = labelLayoutFn(res.annualOverview.annualGraph, title);
  }
  if (res.monthlyDetails && res.monthlyDetails.monthGraph) {
    monthOptions.value = labelLayoutFn(res.monthlyDetails.monthGraph, title);
  }
  midKey.value = Date.now();
};
interface queryForm {
  dateRangeItem?: string;
  level?: string;
  factory?: string;
  startTime?: string;
  endTime?: string;
  month?: string | number;
}

const queryParams = ref<queryForm>({
  dateRangeItem: "",
  factory: "",
  month: new Date().getMonth() + 1
});

const queryTypeParams = ref({
  energyType: 8
});

const loading = ref(false);

const handleChangeTypeFn = (val: number) => {
  queryTypeParams.value.energyType = val;
  labelLayoutAreaFn();
};

const factoryName = ref("");
/** 搜索按钮操作 */
function handleQuery() {
  labelLayoutAreaFn();
}
/** 重置按钮操作 */
function resetQuery() {
  initQuery();
}

// 默认查询条件
const initQuery = () => {
  queryParams.value.factory = "";
  queryParams.value.dateRangeItem = proxy.parseTime(new Date(), "{y}");
  labelLayoutAreaFn();
};
const changeMonth = () => {
  handleQuery();
  emit("monthChange", queryParams.value.month);
};
/** 导出按钮操作 */
const handleDown = async val => {
  if (val == "month") {
    proxy.download("post", "/energy/energyPredictionStatistics/viewMonth/download", monthlyDetails.value, `机械科-高温热水消耗分析预测.xlsx`);
  }
};

onMounted(async () => {
  initQuery();
  systemList.value = await queryDictData({ typeCode: "factoryArea" });
});
</script>

<style lang="scss" scoped>
.energy_consume {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  width: 100%;
  height: 100%;

  :deep(.px-empty .px-empty__image) {
    display: none !important;
  }

  .top_query {
    display: flex;
    flex-flow: row nowrap;
    width: 100%;
    min-width: 1300px;
    height: auto;
    padding: 16px 24px;
    line-height: 44px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 10px 0 rgb(0 37 86 / 12%);

    .tabs {
      display: flex;
      align-items: center;
      justify-content: center;
      line-height: 1;

      /*
      * tab样式
      */
      .tabSwitch {
        padding: 4px;
        margin-right: 20px;
        background-color: #f4f4f4;
        border-radius: 4px;

        :deep(.px-radio-button__inner) {
          background-color: #f4f4f4;
          border: none;
        }

        :deep(.is-active) {
          border: none;

          .px-radio-button__inner {
            background-color: var(--px-color-primary);
            border-radius: 4px;
          }
        }
      }
    }

    .px-form-item {
      margin-bottom: 0;
    }
  }

  .btn-con {
    display: flex;
    gap: 16px;
    justify-content: space-between;

    .btn-bord {
      position: relative;
      width: 100%;
      height: 100%;
      background: #fff;
      border-radius: 4px;
      // box-shadow: 0 2px 10px 0 rgb(0 37 86 / 12%);

      .rightBox {
        position: absolute;
        top: 16px;
        right: 20px;

        .selectMonth {
          width: 80px;
          margin-right: 15px;
        }
      }
    }
  }
}
</style>
